﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Boo.Lang;
using MySql.Data.MySqlClient;

namespace Mite.MySql
{
	public class MySqlAdapter : Adapter
	{
		public override IEnumerable<Database> GetDatabases(IDbConnection connection)
		{
			throw new NotImplementedException();
		}


		protected override DbType ParseDbType(string dataType)
		{
			var param = new MySqlParameter();
			try
			{
				param.MySqlDbType = (MySqlDbType) Enum.Parse(typeof (MySqlDbType), dataType, true);
				return param.DbType;
			}
			catch (ArgumentException ex)
			{
				_logger.Error(ex.Message);
			}
			return DbType.Object;
		}

		public override Database GetDatabase(IDbConnection connection, string name)
		{
			throw new NotImplementedException();
		}

		public override IDbCommand SetSchemaVersion(IDbConnection connection, int i)
		{
			throw new NotImplementedException();
		}

		protected override IDbCommand Insert(IDbConnection connection, string tableName, params object[] values)
		{
			IDbCommand cmd = new MySqlCommand();

			cmd.CommandText = String.Format("INSERT INTO {0} VALUES({1})",
			                                tableName,
			                                String.Join(", ",
			                                            values.Select(
			                                            	v =>
			                                            	v is string || v is DateTime ? "'" + v + "'" : v.ToString())
			                                            	.ToArray()));
			return cmd;
		}


		public override IDbConnection CreateConnection(string host, string database, string username, string password,
		                                               Hash options)
		{
			return new MySqlConnection(BuildConnectionString(host, database, username, password, options));
		}

		public static string BuildConnectionString(string host, string database, string username, string password,
		                                           Hash options)
		{
			string connectionString = String.Format("Server={0};Database={1};", host,
			                                        database);
			if (String.IsNullOrEmpty(username))
			{
				// Assume integrated security
				connectionString += "Integrated Security=true;";
			}
			else
				connectionString += String.Format("Uid={0};Pwd={1}", username, password);

			return connectionString;
		}
	}
}